'use strict';

const path = require('path');
const fs = require('fs');

// 数据库初始化脚本
async function initDatabase() {
  try {
    console.log('开始初始化数据库...');

    // 这里需要手动创建数据库连接
    const mysql = require('mysql2/promise');

    // 从环境变量或配置文件获取数据库配置
    const dbConfig = {
      host: process.env.MySqlHost || '127.0.0.1',
      port: process.env.MySqlPort || 3306,
      user: process.env.MySqlUsername || 'root',
      password: process.env.MySqlPassword || '302108jw302',
    };

    const dbName = process.env.MySqlDatabase || 'wardrobe_db';

    // 创建数据库连接（不指定数据库）
    const connection = await mysql.createConnection(dbConfig);

    // 创建数据库
    await connection.execute(`CREATE DATABASE IF NOT EXISTS \`${dbName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`);
    console.log(`数据库 ${dbName} 创建成功`);

    await connection.end();
    
    // 现在使用Sequelize执行迁移
    const { Sequelize } = require('sequelize');

    const sequelize = new Sequelize(dbName, dbConfig.user, dbConfig.password, {
      host: dbConfig.host,
      port: dbConfig.port,
      dialect: 'mysql',
      logging: console.log,
      define: {
        raw: true,
        underscored: true,
        charset: 'utf8mb4',
        timestamps: true,
        paranoid: true,
        freezeTableName: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at',
      },
      dialectOptions: {
        dateStrings: true,
        typeCast: true,
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci',
      },
      timezone: '+08:00',
    });
    
    // 测试连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 执行迁移文件
    const migrationsDir = path.join(__dirname, 'migrations');
    const migrationFiles = fs.readdirSync(migrationsDir).sort();
    
    for (const file of migrationFiles) {
      if (file.endsWith('.js')) {
        console.log(`执行迁移: ${file}`);
        const migration = require(path.join(migrationsDir, file));
        await migration.up(sequelize.getQueryInterface(), Sequelize);
        console.log(`迁移 ${file} 执行成功`);
      }
    }
    
    // 执行种子数据
    const seedersDir = path.join(__dirname, 'seeders');
    if (fs.existsSync(seedersDir)) {
      const seederFiles = fs.readdirSync(seedersDir).sort();
      
      for (const file of seederFiles) {
        if (file.endsWith('.js')) {
          console.log(`执行种子数据: ${file}`);
          const seeder = require(path.join(seedersDir, file));
          await seeder.up(sequelize.getQueryInterface(), Sequelize);
          console.log(`种子数据 ${file} 执行成功`);
        }
      }
    }
    
    await sequelize.close();
    console.log('数据库初始化完成！');
    
  } catch (error) {
    console.error('数据库初始化失败:', error);
    process.exit(1);
  }
}

// 如果直接运行此文件
if (require.main === module) {
  initDatabase();
}

module.exports = initDatabase;
